//
//  ConversationListController.m
//  ChatDemo-UI3.0
//
//  Created by dhc on 15/6/25.
//  Copyright (c) 2015年 easemob.com. All rights reserved.
//

#import "ConversationListController.h"

#import "EMSearchBar.h"
//#import "EMSearchDisplayController.h"
#import "RealtimeSearchUtil.h"
#import "HXRuntimeStatus.h"
#import "HXDDUserEntity.h"
#import "EMSearchControllerDelegate.h"
#import "UIViewController+SearchController.h"
#import "EaseConvertToCommonEmoticonsHelper.h"
#import "NSDate+HXCategory.h"
#import "UserDTO.h"
#import "NSString+pinyin.h"
@implementation EMConversation (search)

//根据用户昵称、群名称进行搜索
- (NSString*)showName
{
    if (self.type == EMConversationTypeChat) {
        
    } else if (self.type == EMConversationTypeGroupChat) {
        if ([self.ext objectForKey:@"subject"] || [self.ext objectForKey:@"isPublic"]) {
            return [self.ext objectForKey:@"subject"];
        }
    }
    return self.conversationId;
}

@end

@interface ConversationListController ()<EaseConversationListViewControllerDelegate, EaseConversationListViewControllerDataSource,EMSearchControllerDelegate>

@property (nonatomic, strong) UIView *networkStateView;

@property (nonatomic, strong) NSMutableArray * storeUserDTOList;// 存储模型数组
@property (nonatomic, strong) NSMutableArray * searchUserDTOList;// 搜索数组

@end

@implementation ConversationListController

- (void)viewDidLoad {
    [super viewDidLoad];
//    if ([RuntimeStatus instance].ALLUsers.count <1) {
//        [[SynUserandDepartment instance] GetAllUsers];
//    }
    self.showRefreshHeader = YES;
    self.delegate = self;
    self.dataSource = self;
    self.view.backgroundColor = [UIColor whiteColor];
    [self networkStateView];
    
    [self setupSearchController];
    
    //    [self tableViewDidTriggerHeaderRefresh];
    //    [self removeEmptyConversationsFromDB];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self refresh];
    [self tableViewDidTriggerHeaderRefresh];
//    [self removeEmptyConversationsFromDB];//每次返回到“消息”界面就移除空的对话列表。
}
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    //    [_searchController setActive:NO];//页面跳转时，搜索回归初始状态；
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)removeEmptyConversationsFromDB
{
    NSArray *conversations = [[EMClient sharedClient].chatManager getAllConversations];
    NSMutableArray *needRemoveConversations;
    for (EMConversation *conversation in conversations) {
        if (!conversation.latestMessage || (conversation.type == EMConversationTypeChatRoom)) {
            if (!needRemoveConversations) {
                needRemoveConversations = [[NSMutableArray alloc] initWithCapacity:0];
            }
            
            [needRemoveConversations addObject:conversation];
        }
    }
    
    if (needRemoveConversations && needRemoveConversations.count > 0) {
        [[EMClient sharedClient].chatManager deleteConversations:needRemoveConversations isDeleteMessages:YES completion:nil];
    }
}

#pragma mark - getter
- (UIView *)networkStateView
{
    if (_networkStateView == nil) {
        _networkStateView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, 44)];
        _networkStateView.backgroundColor = [UIColor colorWithRed:255 / 255.0 green:199 / 255.0 blue:199 / 255.0 alpha:0.5];
        
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, (_networkStateView.frame.size.height - 20) / 2, 20, 20)];
        imageView.image = [UIImage imageNamed:@"EaseUIResource.bundle/messageSendFail"];
        [_networkStateView addSubview:imageView];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(imageView.frame) + 5, 0, _networkStateView.frame.size.width - (CGRectGetMaxX(imageView.frame) + 15), _networkStateView.frame.size.height)];
        label.font = systemFont(15.0);
        label.textColor = [UIColor grayColor];
        label.backgroundColor = [UIColor clearColor];
        label.text = NSLocalizedString(@"network.disconnection", @"Network disconnection");
        [_networkStateView addSubview:label];
    }
    
    return _networkStateView;
}

#pragma mark - EaseConversationListViewControllerDelegate
//获取点击会话列表的回调
- (void)conversationListViewController:(EaseConversationListViewController *)conversationListViewController
            didSelectConversationModel:(id<IConversationModel>)conversationModel
{
    if (conversationModel) {
        EMConversation *conversation = conversationModel.conversation;
        if (conversation) {
            if (self.jumpToChatDelegate &&
                [self.jumpToChatDelegate respondsToSelector:@selector(IM_jumpToChatViewControllerWithChatter:chatType:)]) {
                [self.jumpToChatDelegate IM_jumpToChatViewControllerWithChatter:conversation.conversationId chatType:(RM_ChatType)conversation.type];
            }else {
                ChatViewController *chatController = [[ChatViewController alloc] initWithConversationChatter:conversation.conversationId conversationType:conversation.type];
                chatController.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:chatController animated:YES];
            }
        }
//        [[NSNotificationCenter defaultCenter] postNotificationName:@"setupUnreadMessageCount" object:nil];
        [self.tableView reloadData];
    }
}

#pragma mark - EaseConversationListViewControllerDataSource

#warning ------ 联系人同步问题  读写易出BUG  待加锁 -------
//获取点击会话列表的回调，
- (id<IConversationModel>)conversationListViewController:(EaseConversationListViewController *)conversationListViewController
                                    modelForConversation:(EMConversation *)conversation
{
    EaseConversationModel *model = [[EaseConversationModel alloc] initWithConversation:conversation];
    if(!model.conversation.ext)
    {
        NSMutableDictionary *ext = [[NSMutableDictionary alloc] init];
        model.conversation.ext = ext;
    }
    if (model.conversation.type == EMConversationTypeChat) {
        if ([conversation.conversationId isEqualToString:@"001"]
            && [HXRuntimeStatus instance].systemServiceTitle)
        {
            NSMutableDictionary *ext = [NSMutableDictionary dictionaryWithDictionary:conversation.ext];
            [ext setObject:[HXRuntimeStatus instance].systemServiceTitle forKey:@"nick"];
            model.conversation.ext = ext;
            model.title = [model.conversation.ext objectForKey:@"nick"];
//            model.avatarImage = [UIImage imageNamed:@"HuanXin.bundle/romens_service"];
            model.avatarImage = [HXRuntimeStatus instance].systemServiceImage;
        }
        else
        {
            for (HXDDUserEntity*user in [HXRuntimeStatus instance].ALLUsers) {
                if([model.title isEqualToString:user.name])
                {
                    // 构造扩展属性
                    NSMutableDictionary *ext = [NSMutableDictionary dictionaryWithDictionary:conversation.ext];
                    [ext setObject:user.nick forKey:@"nick"];
                    [ext setObject:user.avatar forKey:@"avatar"];
                    model.conversation.ext = ext;
                    //  重设会话列表的名称和头像
                    model.title = user.nick;
                    model.avatarURLPath = user.avatar;
                }
            }
        }
    } else if (model.conversation.type == EMConversationTypeGroupChat) {
        NSString *imageName = @"HuanXin.bundle/groupPublicHeader";
        if (![conversation.ext objectForKey:@"subject"])
        {
            NSArray *groupArray = [[EMClient sharedClient].groupManager getJoinedGroups];
            for (EMGroup *group in groupArray) {
                if ([group.groupId isEqualToString:conversation.conversationId]) {
                    NSMutableDictionary *ext = [NSMutableDictionary dictionaryWithDictionary:conversation.ext];
                    [ext setObject:group.subject forKey:@"subject"];
                    [ext setObject:[NSNumber numberWithBool:group.isPublic] forKey:@"isPublic"];
                    conversation.ext = ext;
                    break;
                }
            }
        }
        model.title = [conversation.ext objectForKey:@"subject"];
        imageName = [[conversation.ext objectForKey:@"isPublic"] boolValue] ? @"HuanXin.bundle/groupPublicHeader" : @"HuanXin.bundle/groupPrivateHeader";
        model.avatarImage = [UIImage imageNamed:imageName];
    }
    return model;
}
//显示最后一条消息的内容
- (NSMutableAttributedString *)conversationListViewController:(EaseConversationListViewController *)conversationListViewController
                       latestMessageTitleForConversationModel:(id<IConversationModel>)conversationModel
{
    //    NSString *latestMessageTitle = @"";
    NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:@""];
    EMMessage *lastMessage = [conversationModel.conversation latestMessage];
    if (lastMessage) {
        NSString *latestMessageTitle = @"";
        EMMessageBody *messageBody = lastMessage.body;
        switch (messageBody.type) {
            case EMMessageBodyTypeImage:{
                latestMessageTitle = NSLocalizedString(@"message.image1", @"[image]");
            } break;
            case EMMessageBodyTypeText:{
                // 表情映射。
                NSString *didReceiveText = [EaseConvertToCommonEmoticonsHelper
                                            convertToSystemEmoticons:((EMTextMessageBody *)messageBody).text];
                latestMessageTitle = didReceiveText;
                if ([lastMessage.ext objectForKey:MESSAGE_ATTR_IS_BIG_EXPRESSION]) {
                    latestMessageTitle = @"[动画表情]";
                }
            } break;
            case EMMessageBodyTypeVoice:{
                latestMessageTitle = NSLocalizedString(@"message.voice1", @"[voice]");
            } break;
            case EMMessageBodyTypeLocation: {
                latestMessageTitle = NSLocalizedString(@"message.location1", @"[location]");
            } break;
            case EMMessageBodyTypeVideo: {
                latestMessageTitle = NSLocalizedString(@"message.video1", @"[video]");
            } break;
            case EMMessageBodyTypeFile: {
                latestMessageTitle = NSLocalizedString(@"message.file1", @"[file]");
            } break;
            default: {
            } break;
        }
        if (lastMessage.direction == EMMessageDirectionReceive && lastMessage.chatType == EMChatTypeGroupChat) {
            NSString *from = lastMessage.from;
            HXDDUserEntity *user = [[HXRuntimeStatus instance] GetUserForName:from];
            latestMessageTitle = [NSString stringWithFormat:@"%@: %@",user.nick,latestMessageTitle];
        }
        
        attributedStr = [[NSMutableAttributedString alloc] initWithString:latestMessageTitle];
    }
    
    return attributedStr;
}
//显示最后一条消息的时间
- (NSString *)conversationListViewController:(EaseConversationListViewController *)conversationListViewController
       latestMessageTimeForConversationModel:(id<IConversationModel>)conversationModel
{
    NSString *latestMessageTime = @"";
    EMMessage *lastMessage = [conversationModel.conversation latestMessage];;
    if (lastMessage) {
        latestMessageTime = [NSDate formattedTimeFromTimeInterval:lastMessage.timestamp];
    }
    
    
    return latestMessageTime;
}
#pragma mark -- search Private
- (void)setupSearchController {
    //初始化控制器
    [self enableSearchController];
    
    __weak ConversationListController *weakSelf = self;
    [self.resultController setCellForRowAtIndexPathCompletion:^UITableViewCell *(UITableView *tableView, NSIndexPath *indexPath) {
        NSString *CellIdentifier = [EaseConversationCell cellIdentifierWithModel:nil];
        EaseConversationCell *cell = (EaseConversationCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        
        if (cell == nil) {
            cell = [[EaseConversationCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        }
        
        id<IConversationModel> model = [weakSelf.resultController.displaySource objectAtIndex:indexPath.row];
        cell.model = model;
        
        cell.detailLabel.attributedText = [weakSelf conversationListViewController:weakSelf latestMessageTitleForConversationModel:model];
        cell.timeLabel.text = [weakSelf conversationListViewController:weakSelf latestMessageTimeForConversationModel:model];
        return cell;
    }];
    
    [self.resultController setHeightForRowAtIndexPathCompletion:^CGFloat(UITableView *tableView, NSIndexPath *indexPath) {
        return [EaseConversationCell cellHeightWithModel:nil];
    }];
    
    [self.resultController setDidSelectRowAtIndexPathCompletion:^(UITableView *tableView, NSIndexPath *indexPath) {
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        [weakSelf.searchController.searchBar endEditing:YES];
        id<IConversationModel> model = [weakSelf.resultController.displaySource objectAtIndex:indexPath.row];
        EMConversation *conversation = model.conversation;
        ChatViewController *chatController;
        if (weakSelf.jumpToChatDelegate && [weakSelf.jumpToChatDelegate respondsToSelector:@selector(IM_jumpToChatViewControllerWithChatter:chatType:)]) {
            [weakSelf.jumpToChatDelegate IM_jumpToChatViewControllerWithChatter:conversation.conversationId chatType:(RM_ChatType)conversation.type];
        }else {
            chatController = [[ChatViewController alloc] initWithConversationChatter:conversation.conversationId conversationType:conversation.type];
            chatController.title = [conversation showName];
            [weakSelf.navigationController pushViewController:chatController animated:YES];
        }
//        [[NSNotificationCenter defaultCenter] postNotificationName:@"setupUnreadMessageCount" object:nil];
        [weakSelf.tableView reloadData];
        [weakSelf cancelSearch];
    }];
    
    self.resultController.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    self.resultController.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    UISearchBar *searchBar = self.searchController.searchBar;
    [self.view addSubview:searchBar];
    self.tableView.frame = CGRectMake(0, searchBar.frame.size.height, self.view.frame.size.width,self.view.frame.size.height - searchBar.frame.size.height);
}

#pragma mark -- EMSearchControllerDelegate
- (void)cancelButtonClicked {
    // 结束搜索
    [[RealtimeSearchUtil currentUtil] realtimeSearchStop];
}
- (void)searchButtonClickedWithString:(NSString *)aString {
    //    [self loadSearchData];//加载搜索源数据
    [self startSearch:aString];
    //    __weak typeof(self) weakSelf = self;
    //    [[RealtimeSearchUtil currentUtil] realtimeSearchWithSource:self.dataArray searchText:(NSString *)aString collationStringSelector:@selector(title) resultBlock:^(NSArray *results) {
    //        if (results) {
    //            dispatch_async(dispatch_get_main_queue(), ^{
    //                [weakSelf.resultController.displaySource removeAllObjects];
    //                [weakSelf.resultController.displaySource addObjectsFromArray:results];
    //                [weakSelf.resultController.tableView reloadData];
    //            });
    //        }
    //    }];
}

#pragma mark - UISearchBarDelegate

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    [searchBar setShowsCancelButton:YES animated:YES];
    [self loadSearchData];
    return YES;
}

//- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
//{
////    __weak typeof(self) weakSelf = self;
////    [[RealtimeSearchUtil currentUtil] realtimeSearchWithSource:self.dataArray searchText:(NSString *)searchText collationStringSelector:@selector(title) resultBlock:^(NSArray *results) {
////        if (results) {
////            dispatch_async(dispatch_get_main_queue(), ^{
////                [weakSelf.searchController.resultsSource removeAllObjects];
////                [weakSelf.searchController.resultsSource addObjectsFromArray:results];
////                [weakSelf.searchController.searchResultsTableView reloadData];
////            });
////        }
////    }];
//}

- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar
{
    return YES;
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    searchBar.text = @"";
    [[RealtimeSearchUtil currentUtil] realtimeSearchStop];
    [searchBar resignFirstResponder];
    [searchBar setShowsCancelButton:NO animated:YES];
}

#pragma mark - public

-(void)refresh
{
    [self refreshAndSortView];
}

-(void)refreshDataSource
{
    [self tableViewDidTriggerHeaderRefresh];
}

- (void)isConnect:(BOOL)isConnect{
    if (!isConnect) {
        self.tableView.tableHeaderView = _networkStateView;
    }
    else{
        self.tableView.tableHeaderView = nil;
    }
    
}

- (void)networkChanged:(EMConnectionState)connectionState
{
    if (connectionState == EMConnectionDisconnected) {
        self.tableView.tableHeaderView = _networkStateView;
    }
    else{
        self.tableView.tableHeaderView = nil;
    }
}
#pragma mark --第三方搜索
// 开始所搜
- (void)startSearch:(NSString *)string{
    if (self.searchUserDTOList.count > 0) {
        [self.searchUserDTOList removeAllObjects];
    }
    
    // 开始搜索
    NSString * key = string.lowercaseString;
    NSMutableArray * tempArr = [NSMutableArray array];
    
    if (![key isEqualToString:@"" ] && ![key isEqual:[NSNull null]]) {
        
        [self.storeUserDTOList enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            UserDTO * dto = self.storeUserDTOList[idx];
            
            //担心框架有事后为误转, 再次都设置转为小写
            NSString * name = dto.name.lowercaseString;
            NSString * namePinyin = dto.namePinYin.lowercaseString;
            NSString * nameFirstLetter = dto.nameFirstLetter.lowercaseString;
            
            NSRange rang1 = [name rangeOfString:key];
            if (rang1.length > 0) {
                
                [tempArr addObject:dto];
            }else {
                if ([nameFirstLetter containsString:key]) {
                    
                    [tempArr addObject:dto];
                }else { //
                    if ([nameFirstLetter containsString:[key substringToIndex:1]]) {
                        
                        if ([namePinyin containsString:key]) {
                            [tempArr addObject:dto];
                        }
                    }
                }
            }
            
        }];
        
        [tempArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            if (![self.searchUserDTOList containsObject:tempArr[idx]]) {
                
                [self.searchUserDTOList addObject:tempArr[idx]];
            }
        }];
    }
    [self refreshAfterSearch];
}
- (void)refreshAfterSearch {
    NSMutableArray *resultsArray = [[NSMutableArray alloc] init];
    for (UserDTO *dto in self.searchUserDTOList) {
        for (int i = 0; i<self.dataArray.count; i++) {
            id<IConversationModel> model = [self.dataArray objectAtIndex:i];
            if ([dto.name isEqualToString:model.title]) {
                [resultsArray addObject:model];
            }
        }
    }
    [self.resultController.displaySource removeAllObjects];
    [self.resultController.displaySource addObjectsFromArray:resultsArray];
    [self.resultController.tableView reloadData];
}

- (void)loadSearchData {
    if (self.storeUserDTOList.count > 0) {
        [self.storeUserDTOList removeAllObjects];
    }
    for (int i = 0; i <self.dataArray.count; i++) {
        UserDTO * dto = [[UserDTO alloc] init];
        
        id<IConversationModel> model = [self.dataArray objectAtIndex:i];
        // 转拼音
        NSString * PinYin = [model.title transformToPinyin];
        // 首字母
        NSString * FirstLetter = [model.title transformToPinyinFirstLetter];
        
        dto.name = model.title;
        dto.namePinYin = PinYin;
        dto.nameFirstLetter = FirstLetter;
        
        [self.storeUserDTOList addObject:dto];
    }
}
#pragma mark - 懒加载
//数据源
- (NSMutableArray *)storeUserDTOList{
    if (_storeUserDTOList == nil) {
        _storeUserDTOList = [[NSMutableArray alloc] init];
    }
    return _storeUserDTOList;
}
//结果
- (NSMutableArray *)searchUserDTOList{
    if (_searchUserDTOList == nil) {
        _searchUserDTOList = [[NSMutableArray alloc] init];
    }
    return _searchUserDTOList;
}

@end
